package com.min.gps.service;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.SynchronousQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class BackServer implements Runnable {
    Logger log = LogManager.getLogger(BackServer.class);
    private static Socket socket;

    public void startServer() {

        //服务端在20006端口监听客户端请求的TCP连接
        ServerSocket server = null;
        try {
            server = new ServerSocket(1123, 10000);
            ExecutorService pool = new ThreadPoolExecutor(0, 10000,
                    20L, TimeUnit.SECONDS,
                    new SynchronousQueue<>());

            while (true) {
                //等待客户端的连接，如果没有获取连接
                Socket socket = server.accept();
                //为每个客户端连接开启一个线程
                pool.execute(new BackServer(socket));
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


    }

    public BackServer(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {

        while (true) {//保持长连接
            try {
                Thread.sleep(1000);//等待时间
            } catch (InterruptedException e1) {
                e1.printStackTrace();
            }
            if (socket != null) {
               try {
                     BufferedReader buf = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                     PrintStream out = new PrintStream(socket.getOutputStream());
                    socket.setKeepAlive(true);
                log.info("后端服务收到推送消息===================="+buf.readLine());

                } catch (Exception e) {
                   e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        BackServer server = new BackServer(socket);
        server.startServer();
    }
}
